package com.tianji.aigc.service.impl;

import java.nio.ByteBuffer;
import java.util.concurrent.CountDownLatch;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.cloud.ai.dashscope.audio.synthesis.SpeechSynthesisModel;
import com.alibaba.cloud.ai.dashscope.audio.synthesis.SpeechSynthesisPrompt;
import com.alibaba.cloud.ai.dashscope.audio.synthesis.SpeechSynthesisResponse;
import com.tianji.aigc.service.AudioService;

import lombok.RequiredArgsConstructor;
import reactor.core.publisher.Flux;

@Service
@RequiredArgsConstructor
public class AudioServiceImpl implements AudioService {
    Logger logger = LoggerFactory.getLogger(AudioServiceImpl.class);
    private final SpeechSynthesisModel speechSynthesisModel;

    public Flux<SpeechSynthesisResponse> streamTTS(String text) {
        logger.info("开始调用dashscope的tts服务");
        Flux<SpeechSynthesisResponse> response = speechSynthesisModel.stream(new SpeechSynthesisPrompt(text));

        CountDownLatch latch = new CountDownLatch(1);
        try {
            logger.info("合成" + text);
            response.doFinally(signal -> latch.countDown()).subscribe(synthesisResponse -> {
                ByteBuffer byteBuffer = synthesisResponse.getResult().getOutput().getAudio();
                byte[] bytes = new byte[byteBuffer.remaining()];
                byteBuffer.get(bytes);
            });
            return response;
        } catch (Exception e) {
            logger.error("语音合成失败", e);
            throw new RuntimeException(e);
        }
    }

}
